package com.github.ecbp.common.security.vo;

import lombok.Data;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Data
public class DefaultSecurityConfig implements ConfigAttribute {

    private String attribute;

    public DefaultSecurityConfig() {
    }

    public DefaultSecurityConfig(String config) {
        Assert.hasText(config, "You must provide a configuration attribute");
        this.attribute = config;
    }

    // ~ Methods
    // ========================================================================================================

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof ConfigAttribute) {
            ConfigAttribute attr = (ConfigAttribute) obj;

            return this.attribute.equals(attr.getAttribute());
        }

        return false;
    }

    @Override
    public String getAttribute() {
        return this.attribute;
    }

    @Override
    public int hashCode() {
        return this.attribute.hashCode();
    }

    @Override
    public String toString() {
        return this.attribute;
    }

    public static List<ConfigAttribute> createListFromCommaDelimitedString(String access) {
        return createList(StringUtils.commaDelimitedListToStringArray(access));
    }

    public static List<ConfigAttribute> createList(String... attributeNames) {
        Assert.notNull(attributeNames, "You must supply an array of attribute names");
        List<ConfigAttribute> attributes = new ArrayList<>(
                attributeNames.length);

        for (String attribute : attributeNames) {
            attributes.add(new org.springframework.security.access.SecurityConfig(attribute.trim()));
        }

        return attributes;
    }
}